package com.example.farmeri.tools;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import androidx.lifecycle.MutableLiveData;

import com.example.farmeri.common.MyCallback;
import com.example.farmeri.http.ComInterceptor;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Create by weiqishan on 2020/5/11.
 */
public class OKHttpClientUtils {

    public static final int TYPE_TEXT = 0x10;
    public static final int TYPE_FILE = 0x11;
    public static final int TYPE_FORM = 0x12;

    private static OkHttpClient client;

    static {
        if (client == null){
            synchronized (OKHttpClientUtils.class){
                if (client == null){
                    client = new OkHttpClient.Builder()
                            .addInterceptor(new ComInterceptor())
                            .build();
                }
            }
        }
    }

    public static OkHttpClient getInstance(){
        if (client == null){
            synchronized (OKHttpClientUtils.class){
                if (client == null){
                    client = new OkHttpClient.Builder()
                            .addInterceptor(new ComInterceptor())
                            .build();
                }
            }
        }
        return client;
    }


    void test(){

        MutableLiveData<Object> m = new MutableLiveData();
        Handler handler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
            }
        };
    }

    public static void userGet(String url, Callback callback){
        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(callback);
    }


    public static <T>void useGetS(String url, Map<String ,T> para, Callback callback){
        StringBuilder sb = new StringBuilder();
        sb.append(url);

        Iterator<Map.Entry<String, T>> entries = para.entrySet().iterator();
        if (entries.hasNext()){
            Map.Entry<String, T> entry = entries.next();
            sb.append("?");
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(entry.getValue());
        }

        while (entries.hasNext()) {
            Map.Entry<String, T> entry = entries.next();
            sb.append("&");
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(entry.getValue().toString());
        }

        Log.e("TAG", "userGetS: sb =" +sb.toString() );
        System.out.println(sb.toString());
        Request request = new Request.Builder()
                .url(sb.toString())
                .build();

        client.newCall(request).enqueue(callback);
    }

    /**
     * 单纯的提交字符串
     * @param url
     * @param data
     * @param callback
     */
    public static void userPost4String(String url,String data, Callback callback){
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"),data))
                .build();

        client.newCall(request).enqueue(callback);
    }

    /**
     * 可以提交任何类型
     * @param url
     * @param type
     * @param data
     * @param callback
     * @param <T>
     */
    public static <T> void  userPost(String url,int type,T data, Callback callback){
        if(null == data){
            Log.e("TAG", "userPost: data is null");
            return;
        }
        Request.Builder builder = new Request.Builder();
        Log.e("TAG", "userPost: url =" +url );
        builder.url(url);
        if (type == TYPE_TEXT  ||  type == TYPE_FILE){
            if (data instanceof String  ||  data instanceof File){
                builder.post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"),(String)data));
            }else {
                Log.e("OkHttpClientUtils", "userPost: 参数传递错误" );
            }
        }else if(type == TYPE_FILE){

        }else if (type == TYPE_FORM){
            if (data instanceof Map){
                FormBody.Builder formBuilder = new FormBody.Builder();
                Map<String ,T> map = (HashMap<String, T>) data;

                for (Map.Entry<String, T> entry : map.entrySet()) {
                    formBuilder.add(entry.getKey(),entry.getValue().toString());
                }

                builder.post(formBuilder.build());
            }else {
                Log.e("OkHttpClientUtils", "userPost: 参数传递错误" );
            }
        }

        client.newCall(builder.build()).enqueue(callback);
    }

    /**
     * 可以提交任何类型
     * @param url
     * @param type
     * @param data
     * @param callback
     * @param <T>
     */
    public static <T> void  userPost4EvenBus(String url,int type,T data, MyCallback callback){
        Request.Builder builder = new Request.Builder();
        Log.e("TAG", "userPost: url =" +url );
        builder.url(url);
        if (type == TYPE_TEXT  ||  type == TYPE_FILE){
            if (data instanceof String  ||  data instanceof File){
                builder.post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"),(String)data));
            }
        }else if(type == TYPE_FILE){

        }else if (type == TYPE_FORM){
            if (data instanceof Map){
                FormBody.Builder formBuilder = new FormBody.Builder();
                Map<String ,T> map = (HashMap<String, T>) data;

                for (Map.Entry<String, T> entry : map.entrySet()) {
                    formBuilder.add(entry.getKey(),entry.getValue().toString());
                }

                builder.post(formBuilder.build());
            }
        }

        client.newCall(builder.build()).enqueue(callback);
    }


}


